# -*- coding: utf-8 -*-
# config/settings.py
"""
应用配置文件
"""

import os
from typing import Dict, Any, List
from pydantic_settings import BaseSettings
try:
    # 尝试导入 v2 版本的 Field
    from pydantic.fields import Field
except ImportError:
    #  fallback 到 v1 版本
    from pydantic import Fiel
from pathlib import Path

class Settings(BaseSettings):
    """应用设置"""
    
    # 基础配置
    APP_NAME: str = "Smart AI Chat"
    APP_VERSION: str = "2.0.0"
    DEBUG: bool = Field(default=False, env="DEBUG")
    
    # API密钥配置
    OPENAI_API_KEY: str = Field(default="", env="OPENAI_API_KEY")
    ANTHROPIC_API_KEY: str = Field(default="", env="ANTHROPIC_API_KEY")
    GOOGLE_API_KEY: str = Field(default="", env="GOOGLE_API_KEY")
    
    # 数据库配置
    DATABASE_URL: str = Field(default="sqlite:///data/app.db", env="DATABASE_URL")
    VECTOR_DB_PATH: str = Field(default="data/vectordb", env="VECTOR_DB_PATH")
    
    # LangChain配置
    LANGCHAIN_TRACING_V2: bool = Field(default=True, env="LANGCHAIN_TRACING_V2")
    LANGCHAIN_API_KEY: str = Field(default="", env="LANGCHAIN_API_KEY")
    LANGCHAIN_PROJECT: str = Field(default="smart-ai-chat", env="LANGCHAIN_PROJECT")
    
    # 模型配置
    DEFAULT_MODEL: str = "gpt-4"
    MAX_TOKENS: int = 2000
    TEMPERATURE: float = 0.7
    
    # 文件路径
    DATA_DIR: Path = Path("data")
    CONVERSATIONS_DIR: Path = DATA_DIR / "conversations"
    UPLOADS_DIR: Path = DATA_DIR / "uploads"
    CONFIG_DIR: Path = DATA_DIR / "config"
    
    # UI配置
    PAGE_TITLE: str = "🤖 智能AI群聊系统"
    PAGE_ICON: str = "🤖"
    LAYOUT: str = "wide"
    
    class Config:
        env_file = ".env"
        case_sensitive = True

# 支持的AI模型配置
SUPPORTED_MODELS = {
    "gpt-4": {
        "name": "GPT-4",
        "provider": "OpenAI",
        "description": "最先进的大语言模型",
        "avatar": "🧠",
        "color": "#10a37f",
        "max_tokens": 4096
    },
    "gpt-3.5-turbo": {
        "name": "GPT-3.5 Turbo",
        "provider": "OpenAI", 
        "description": "快速响应的对话模型",
        "avatar": "⚡",
        "color": "#10a37f",
        "max_tokens": 4096
    },
    "claude-3": {
        "name": "Claude-3",
        "provider": "Anthropic",
        "description": "Claude-3 Sonnet模型",
        "avatar": "🤖",
        "color": "#d97706",
        "max_tokens": 4096
    },
    "gemini-pro": {
        "name": "Gemini Pro",
        "provider": "Google",
        "description": "Google的多模态AI模型",
        "avatar": "💎", 
        "color": "#4285f4",
        "max_tokens": 2048
    },
    "wenxin": {
        "name": "文心一言",
        "provider": "百度",
        "description": "百度开发的中文大语言模型",
        "avatar": "🪷",
        "color": "#2932e1",
        "max_tokens": 4096
    },
    "qwen": {
        "name": "通义千问",
        "provider": "阿里云",
        "description": "阿里云开发的多轮对话模型",
        "avatar": "🕌",
        "color": "#ff6a00",
        "max_tokens": 6000
    },
    "doubao": {
        "name": "豆包",
        "provider": "字节跳动",
        "description": "字节跳动开发的AI助手",
        "avatar": "🫘",
        "color": "#fe2c55",
        "max_tokens": 4096
    }
}

# 创建设置实例
settings = Settings()

# 确保数据目录存在
for directory in [
    settings.DATA_DIR,
    settings.CONVERSATIONS_DIR, 
    settings.UPLOADS_DIR,
    settings.CONFIG_DIR
]:
    directory.mkdir(parents=True, exist_ok=True)

def load_api_keys() -> Dict[str, str]:
    """
    从环境变量或配置文件中加载API密钥
    
    返回:
        Dict[str, str]: 包含所有模型API密钥的字典
    """
    # 从环境变量加载API密钥
    api_keys = {
        "openai": os.environ.get("OPENAI_API_KEY", settings.OPENAI_API_KEY),
        "anthropic": os.environ.get("ANTHROPIC_API_KEY", settings.ANTHROPIC_API_KEY),
        "google": os.environ.get("GOOGLE_API_KEY", settings.GOOGLE_API_KEY),
        "baidu": os.environ.get("BAIDU_API_KEY", ""),
        "aliyun": os.environ.get("ALIYUN_API_KEY", ""),
        "bytedance": os.environ.get("BYTEDANCE_API_KEY", "")
    }
    
    # 尝试从配置文件加载API密钥
    config_file = settings.CONFIG_DIR / "api_keys.json"
    if config_file.exists():
        try:
            import json
            with open(config_file, "r", encoding="utf-8") as f:
                config_keys = json.load(f)
                # 更新API密钥，优先使用配置文件中的密钥
                for provider, key in config_keys.items():
                    if key:  # 只有当密钥不为空时才更新
                        api_keys[provider] = key
        except Exception as e:
            print(f"加载API密钥配置文件失败: {e}")
    
    return api_keys